//
//  MobCpuInfoViewController.m
//  ebook
//
//  Created by 吴超飞 on 2016/11/25.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "MobCpuInfoViewController.h"
#import "BaiduMobAdSDK/BaiduMobCpuInfoManager.h"
#import "HeadTabBar.h"
#import <SVProgressHUD.h>
#import "WebViewController.h"
#import "MobChannelEditController.h"

@interface MobCpuInfoViewController ()<UIWebViewDelegate,HeadTabBarDelegate>

@property (nonatomic, strong) HeadTabBar *headTabBar;
@property (nonatomic, retain) NSMutableArray *dataArray;//我的频道
@property (nonatomic, retain) NSMutableArray *bottomChannelArr;//推荐频道
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, retain) UIView *coverView;

@end

@implementation MobCpuInfoViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
  
    [self creatNavigationItem];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"发现头条";
    self.tabBarItem.title = @"发现";
    
    [self initHeadTabbar];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
}

-(UIWebView *)webView{
    
    if(!_webView){
        float y = 44;
        _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, y, MTScreenW, MTScreenH - 49 -SafeAreaTopHeight -y)];
        _webView.backgroundColor = [UIColor whiteColor];
        _webView.delegate = self;
        _webView.scalesPageToFit = YES;
        _webView.scrollView.bounces = NO;
    }
    
    return _webView;
}

#pragma mark - 顶部选择条
-(void)initHeadTabbar{
    
    [self.view addSubview:self.webView];
    self.headTabBar = [[HeadTabBar alloc] init];
    self.headTabBar.delegate = self;
    [self.view addSubview:self.headTabBar];
    
    //先获取用户自定义数据，获取不到则使用系统默认
    NSArray *dictArray = [[NSArray alloc] initWithContentsOfFile:UserChannelPlistFilePath];
    if(!dictArray||dictArray.count==0)
        dictArray=[[NSArray alloc] initWithContentsOfFile:ChannelPlistFilePath];
    
    if(!_dataArray)_dataArray = [NSMutableArray array];
    if(!_bottomChannelArr)_bottomChannelArr = [NSMutableArray array];
    [dictArray enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ChannelUnitModel *unit = [[ChannelUnitModel alloc] initWithDict:obj];
        if(unit.IsAdd)[_dataArray addObject:unit];
        else [_bottomChannelArr addObject:unit];
    }];
    
    self.headTabBar.itemArray = _dataArray;
    
    [self loadChannel:[_dataArray firstObject]];
}

-(void)headTabBar:(HeadTabBar *)view didSelectedItem:(ChannelUnitModel *)item{
    [self loadChannel:item];
}

-(void)headTabBar:(HeadTabBar *)view addBtnClick:(UIButton *)addBtn{
    
    MobChannelEditController *channelEdit = [[MobChannelEditController alloc] initWithTopDataSource:self.dataArray andBottomDataSource:self.bottomChannelArr andInitialIndex:[self.dataArray indexOfObject:_headTabBar.currentChanel]];
    
    //编辑后的回调
    __weak MobCpuInfoViewController *weakSelf = self;
    channelEdit.removeInitialIndexBlock = ^(NSMutableArray<ChannelUnitModel *> *topArr, NSMutableArray<ChannelUnitModel *> *bottomArr){
        weakSelf.dataArray = topArr;
        weakSelf.bottomChannelArr = bottomArr;
        ChannelUnitModel *current = _headTabBar.currentChanel;
        if (![weakSelf.dataArray containsObject:current]) {
            current = [topArr firstObject];
        }
        [weakSelf.headTabBar reloadData:topArr currentChannel:current];
        [weakSelf saveData];
    };
    channelEdit.chooseIndexBlock = ^(ChannelUnitModel *selectModel, NSMutableArray<ChannelUnitModel *> *topArr, NSMutableArray<ChannelUnitModel *> *bottomArr){
        weakSelf.dataArray = topArr;
        weakSelf.bottomChannelArr = bottomArr;
        [weakSelf.headTabBar reloadData:topArr currentChannel:selectModel];
        [weakSelf saveData];
    };
    
    channelEdit.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:channelEdit animated:YES completion:nil];
}

//保存数据的修改
-(void)saveData{
    NSMutableArray *dictArray = [NSMutableArray array];
    [self.dataArray enumerateObjectsUsingBlock:^(ChannelUnitModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.IsAdd = YES;
        NSDictionary *dict = [obj dictWithModel];
        [dictArray addObject:dict];
    }];
    [self.bottomChannelArr enumerateObjectsUsingBlock:^(ChannelUnitModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.IsAdd = NO;
        NSDictionary *dict = [obj dictWithModel];
        [dictArray addObject:dict];
    }];
    BOOL isSuc = [dictArray writeToFile:UserChannelPlistFilePath atomically:YES];
    MTLog(@"写入菜单配置数据成功？%d",isSuc);
}

#pragma mark - NavigationItem
-(void)creatNavigationItem{
    
    UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"home_icon"] style:UIBarButtonItemStylePlain target:self action:@selector(homeBtnClick:)];
    rightBarBtn.tintColor = MTConfigColor(@"MTNavigationBar_rightItem_Color");
    self.navigationItem.rightBarButtonItem = rightBarBtn;
    
    UIBarButtonItem *leftBarBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_arrow"] style:UIBarButtonItemStylePlain target:self action:@selector(backBtnClick:)];
    leftBarBtn.tintColor = MTConfigColor(@"MTNavigationBar_leftItem_Color");
    self.navigationItem.leftBarButtonItem = leftBarBtn;
}

-(void)homeBtnClick:(UIBarButtonItem *)item{
    
    self.tabBarController.selectedIndex = 1;
}

-(void)backBtnClick:(UIBarButtonItem *)item{
    
    self.tabBarController.selectedIndex = 0;
}

-(void)loadChannel:(ChannelUnitModel *)model{
    
    NSString *urlStr = [[BaiduMobCpuInfoManager shared] getCpuInfoUrlWithChannelId:model.ID appId:kBaiduMobAdPublisherId];
    MTLog(@"选中url:%@", urlStr);
    if (urlStr) {
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60]];
    }
}

- (UIWebView*)duplicate:(UIWebView*)view
{
    NSData * tempArchive = [NSKeyedArchiver archivedDataWithRootObject:view];
    return [NSKeyedUnarchiver unarchiveObjectWithData:tempArchive];
}

#pragma mark - UIWebviewDelegate
-(void)webViewDidStartLoad:(UIWebView *)webView
{
    [SVProgressHUD show];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{//倒计时移除视图
        [SVProgressHUD dismiss];
    });
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    if(error.code == -1009)
        [self showFailView];
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    [SVProgressHUD dismiss];
    [self hiddenFailView];
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"]; //UIWebView内存占用过高、崩溃、内存溢出
//    MTLog(@"加载完成，内容为：%@",[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerHTML"]);
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSString *hostname = request.URL.host.lowercaseString;
    NSString *currenturlHost = webView.request.URL.host.lowercaseString;
    if (navigationType == UIWebViewNavigationTypeFormSubmitted||navigationType ==UIWebViewNavigationTypeLinkClicked||(navigationType == UIWebViewNavigationTypeOther && hostname && currenturlHost && ![hostname isEqualToString:currenturlHost]))
    {
        WebViewController *webv = [[WebViewController alloc] init];
        webv.isDirectLoadReques = YES;
        webv.isShowToolbar = YES;
        webv.webViewTitle = _headTabBar.currentChanel.Name;
        webv.request = request;
        [self.navigationController pushViewController:webv animated:YES];
        
        return false;
    }
    
    return true;
}

#pragma mark - FailView
- (void)showFailView
{
    [SVProgressHUD dismiss];
    [self.view addSubview:self.coverView];
    [self.view bringSubviewToFront:self.coverView];
}

- (void)hiddenFailView
{
    if (!self.isNetConnect) {//网络没有连接
        
    } else {//网络有连接
        [_coverView removeFromSuperview];
        _coverView = nil;
    }
}

-(UIView *)coverView
{
    if (!_coverView) {
        
        _coverView = [[UIView alloc] init];
        _coverView.frame = CGRectMake(0, CGRectGetMaxY(self.headTabBar.frame), MTScreenW, MTScreenH-SafeAreaTopHeight);
        _coverView.backgroundColor = MTConfigColor(@"MTBookCity_CoverViewBg_Color");//使用图片一样的背景色
        
        UIImage *image = [UIImage imageNamed:@"loadFail"];
        UIImageView *icon = [[UIImageView alloc] init];
        icon.frame = CGRectMake((MTScreenW-208)/2, 40, 208, 256);
        icon.image = image;
        icon.userInteractionEnabled = YES;
        [_coverView addSubview:icon];
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.frame = CGRectMake(0, CGRectGetMaxY(icon.frame), MTScreenW, 80);
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.text = @"连接失败，请检查网络连接\n点击屏幕重试";
        titleLabel.numberOfLines = 2;
        
        titleLabel.font = [UIFont systemFontOfSize:16.0];
        titleLabel.textColor = MTConfigColor(@"MTBookCity_titleLabelText_Color");
        [_coverView addSubview:titleLabel];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(reloadView)];
        [self.view addGestureRecognizer:tap];
    }
    
    return _coverView;
}

- (void)reloadView{
    
    [SVProgressHUD dismiss];
    [self loadChannel:_headTabBar.currentChanel];
    [self hiddenFailView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
